package com.zhongan.gateway.filter;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zhongan.gateway.bean.Api;
import com.zhongan.gateway.bean.ApiPrivilege;
import com.zhongan.gateway.bean.Developer;
import com.zhongan.gateway.common.enums.GatewayErrorCodeEnum;
import com.zhongan.gateway.common.exception.GatewayException;
import com.zhongan.gateway.dto.RequestBase;
import com.zhongan.gateway.service.ApiPrivilegeService;

/**
 * 对ip流量进行控制
 */
@Component
public class ApiPrivilegeZuulFilter extends ZuulFilter {
    private Logger log = LoggerFactory.getLogger(ApiPrivilegeZuulFilter.class);
    @Resource
    private ApiPrivilegeService apiPrivilegeService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 12;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        RequestBase re = (RequestBase) request.getAttribute("requestBase");
        Developer developer = (Developer) request.getAttribute("developer");
        Api api = (Api) request.getAttribute("api");
        try {

            List<ApiPrivilege> list = apiPrivilegeService.selectPrivileges(developer.getId(), api.getId());
            //权限校验
            if (list == null || list.isEmpty()) {
                throw new GatewayException(GatewayErrorCodeEnum.AUTH_ERROR.getCode(), "无权访问该api,serviceName="
                        + re.getServiceName() + ",appKey=" + re.getAppKey());
            }
            //流量限制
            ApiPrivilege ap = list.get(0);
            if (null != ap.getThrottledCntBySec() && ap.getThrottledCntBySec() > 0) {
                request.setAttribute("overFlow", initOverFlowString(ap));
            }

        } catch (GatewayException ge) {
            log.warn(ge.getMessage());
            request.setAttribute("gatewayException", ge);
            throw new RuntimeException();
        }
        log.info("权限校验成功...");
        return null;
    }

    private String initOverFlowString(ApiPrivilege ap) {
        String s = ap.getId() + "_" + ap.getThrottledCntBySec();
        return s;
    }
}
